// 9、useEffect中发送请求、ajax查询、添加、删除操作、ajax编辑和修改、ajax分页
// 查询、使用useRef获取DOM元素
import React, {useEffect, useState, useRef,Component} from 'react';
import './Nine.css'
import axios from 'axios'

class Son extends Component {
    state = {
        name : '张三',
        age :13
    }
    render() {
        return (
            <div>Son</div>
        )
    }
}

function Nine(props) {
    // 定义一个ref引用，用于绑定dom元素或组件(注意：组件必须是类组件,如果是函数式组件获取不到)
    let h2Ref = useRef(null)
    let sonRef = useRef(null)
    // 定义状态
    // 当前页
    let [pageIndex, setPageIndex] = useState(1)
    // 总页数
    let [totalPage, setTotalPage] = useState(1)
    let [subject, setSubject] = useState({
        subjectName: '',
        classHour: '',
        gradeId: ''
    })
    let [grades, setGrades] = useState([])
    let [subjects, setSubjects] = useState([])

    // useEffect不能直接使用async如果需要，可以在内部定义一个函数来实现
    useEffect(() => {
        async function loadGrades() {
            let {data} = await axios.get('https://bingjs.com:8001/Grade/GetAll')
            console.log(data)
            setGrades(data)
        }

        loadGrades()
    }, [])

    useEffect(() => {
        // 组件挂载时加载课程信息,pageIndex每次更新后重新加载课程信息
        loadSubjects()
    }, [pageIndex])

    // 加载课程列表的方法
    async function loadSubjects() {
        let {data: {data, count}} = await axios.get('https://bingjs.com:8001/Subject/GetSubjectsConditionPages', {
            params: {
                pageIndex
            }
        })
        setSubjects(data)
        setTotalPage(Math.ceil(count / 10))
    }

    // 更新课程状态方法
    const changeSubject = (e, type) => {
        setSubject({
            ...subject,
            [type]: e.target.value
        })
    }
    // 取消方法
    const cancel = () => {
        setSubject({
            subjectName: '',
            classHour: '',
            gradeId: ''
        })
    }
    // 添加方法
    const add = async () => {
        if (!subject.subjectName || !subject.classHour || !subject.gradeId) {
            return alert('请输入完整信息！')
        }
        let {data} = await axios.post('https://bingjs.com:8001/Subject/Add', subject)
        console.log(data)
        if (data) {
            alert('添加成功')
            loadSubjects()
            cancel()
        }
    }
    // 删除方法
    const del = async (subjectId) => {
        if (!window.confirm('确定删除吗')) return
        let {data} = await axios.post('https://bingjs.com:8001/Subject/Delete', {subjectId})
        if (data) {
            alert('删除成功')
            loadSubjects()
        }
    }
    // 编辑方法
    const edit = async (subjectId) => {
        let {data} = await axios.get('https://bingjs.com:8001/Subject/GetSubjectById', {params: {subjectId}})
        console.log(data)
        setSubject({
            subjectId: data.SubjectId,
            subjectName: data.SubjectName,
            classHour: data.ClassHour,
            gradeId: data.GradeId
        })
    }
    // 修改方法
    const update = async () => {
        if (!subject.subjectName || !subject.classHour || !subject.gradeId) {
            return alert('请输入完整信息！')
        }
        let {data} = await axios.post('https://bingjs.com:8001/Subject/update', subject)
        if (data) {
            alert('修改成功！')
            loadSubjects()
        }
    }
    const setTitle = () => {
        h2Ref.current.innerHTML = '学生管理'
        h2Ref.current.style.color = 'red'
        console.log(sonRef)
    }
    return (
        <div className='title'>
            <h2>Nine</h2>
            <button onClick={setTitle}>修改标题</button>
            <h2 ref={h2Ref}>课程管理</h2>
            <table>
                <tbody>
                <tr>
                    <td>名称：</td>
                    <td><input type="text" value={subject.subjectName} onChange={(e) => {
                        changeSubject(e, 'subjectName')
                    }}/></td>
                </tr>
                <tr>
                    <td>课时：</td>
                    <td><input type="text" value={subject.classHour} onChange={(e) => {
                        changeSubject(e, 'classHour')
                    }}/></td>
                </tr>
                <tr>
                    <td>年级：</td>
                    <td>
                        <select value={subject.gradeId} onChange={(e) => {
                            changeSubject(e, 'gradeId')
                        }}>
                            {

                                grades.map(item => {
                                    return <option key={item.GradeId} value={item.GradeId}>{item.GradeName}</option>
                                })
                            }
                        </select>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        {
                            subject.subjectId ? <button onClick={update}>修改</button> :
                                <button onClick={add}>添加</button>
                        }
                        <button onClick={cancel}>取消</button>
                    </td>
                </tr>
                </tbody>
            </table>
            <table>
                <thead>
                <tr>
                    <th>编号</th>
                    <th>名称</th>
                    <th>课时</th>
                    <th>年级</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                {
                    subjects.map((item) => {
                        return (
                            <tr key={item.SubjectId}>
                                <td>{item.SubjectId}</td>
                                <td>{item.SubjectName}</td>
                                <td>{item.ClassHour}</td>
                                <td>{item.Grade.GradeName}</td>
                                <td>
                                    <button onClick={() => {
                                        edit(item.SubjectId)
                                    }}>编辑
                                    </button>
                                    <button onClick={() => {
                                        del(item.SubjectId)
                                    }}>删除
                                    </button>
                                </td>
                            </tr>
                        )
                    })
                }
                </tbody>
                <tfoot>
                <tr>
                    <td colSpan='5'>
                        <button onClick={() => {
                            pageIndex >= 1 && setPageIndex(1)
                        }}>首页
                        </button>
                        <button onClick={() => {
                            pageIndex > 1 && setPageIndex(--pageIndex)
                        }}>上一页
                        </button>
                        <span>{pageIndex}</span>
                        <span>/</span>
                        <span>{totalPage}</span>
                        <button onClick={() => {
                            pageIndex < totalPage && setPageIndex(++pageIndex)
                        }}>下一页
                        </button>
                        <button onClick={() => {
                            pageIndex < totalPage && setPageIndex(totalPage)
                        }}>尾页
                        </button>
                    </td>
                </tr>
                </tfoot>
            </table>
            <Son ref={sonRef}></Son>
        </div>
    );
}

export default Nine;
